package top.fyukina.fyson.runtime.loader;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import top.fyukina.fyson.runtime.exception.FunctionNotFoundException;
import top.fyukina.fyson.runtime.exception.FysonException;
import top.fyukina.fyson.runtime.exception.FysonRuntimeException;
import top.fyukina.fyson.runtime.exception.UninitializedException;

public final class FunctionLoader {
    private static JSONArray funcs = null;
    private FunctionLoader() {}
    public static void init(JSONArray fun) {
        funcs = fun;
    }
    public static Object load(String name, Object arg) throws FysonException {
        if (funcs == null) throw new UninitializedException("functions");
        if (!(arg instanceof JSONArray)) throw new FysonRuntimeException("Function parameter error");
        for (Object fun : funcs) {
            if (fun instanceof JSONObject fun0) {
                String n = fun0.getString("name");
                if (n == null || !n.equals(name)) continue;
                JSONArray a = fun0.getJSONArray("param");
                if (a == null || a.size() != ((JSONArray) arg).size())
                    throw new FysonRuntimeException("Function parameter error");
            }
        }
        throw new FunctionNotFoundException(name);
    }
}